﻿using System;
using System.Runtime.InteropServices;

namespace DAL.Process
{
    public class ProcessAccess: IProcessAccess
    {
        #region IProcessAccess Members

        public string GetActiveProcessName()
        {
            try
            {
                return GetActiveProcess().ProcessName;                
            } 
            catch
            {
                return null;
            }
        }

        public string GetActiveProcessTitle()
        {
            try
            {
                return GetActiveProcess().MainWindowTitle;
            }
            catch
            {
                return null;
            }            
        }

        #endregion

        [DllImport("user32.dll")]
        private extern static Int32 GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

        [DllImport("user32.dll")]
        private extern static IntPtr GetForegroundWindow();

        private System.Diagnostics.Process GetProcessByHandle(IntPtr hwnd)
        {
            try
            {
                uint processId;
                GetWindowThreadProcessId(hwnd, out processId);
                return System.Diagnostics.Process.GetProcessById((int)processId);
            }
            catch { return null; }
        }

        private System.Diagnostics.Process GetActiveProcess()
        {
            var hwnd = GetForegroundWindow();
            return hwnd != IntPtr.Zero ? GetProcessByHandle(hwnd) : null;
        }
    }
}
